package com.yuelao.yuelao_backend.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yuelao.yuelao_backend.entity.Conversation;
import com.yuelao.yuelao_backend.mapper.ConversationMapper;
import com.yuelao.yuelao_backend.mapper.MessageMapper;
import com.yuelao.yuelao_backend.service.ConversationService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 会话Service实现类
 * 重构说明：新增，用于管理私聊会话
 */
@Service
@RequiredArgsConstructor
public class ConversationServiceImpl extends ServiceImpl<ConversationMapper, Conversation> implements ConversationService {

    private final MessageMapper messageMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Conversation getOrCreateConversation(Long user1Id, Long user2Id) {
        // 查询是否已存在会话（不分顺序）
        LambdaQueryWrapper<Conversation> wrapper = new LambdaQueryWrapper<>();
        wrapper.and(w -> w.eq(Conversation::getUserId1, user1Id).eq(Conversation::getUserId2, user2Id))
               .or(w -> w.eq(Conversation::getUserId1, user2Id).eq(Conversation::getUserId2, user1Id));
        
        Conversation conversation = getOne(wrapper);
        
        if (conversation == null) {
            // 创建新会话
            conversation = new Conversation();
            conversation.setUserId1(Math.min(user1Id, user2Id)); // 保证userId1 < userId2
            conversation.setUserId2(Math.max(user1Id, user2Id));
            conversation.setCreatedAt(LocalDateTime.now());
            conversation.setUpdatedAt(LocalDateTime.now());
            save(conversation);
        }
        
        return conversation;
    }

    @Override
    public List<Conversation> getUserConversations(Long userId) {
        LambdaQueryWrapper<Conversation> wrapper = new LambdaQueryWrapper<>();
        wrapper.and(w -> w.eq(Conversation::getUserId1, userId)
                         .or()
                         .eq(Conversation::getUserId2, userId))
               .orderByDesc(Conversation::getLastMessageTime);
        
        return list(wrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateLastMessage(Long conversationId, Long lastMessageId) {
        Conversation conversation = getById(conversationId);
        if (conversation != null) {
            conversation.setLastMessageId(lastMessageId);
            conversation.setLastMessageTime(LocalDateTime.now());
            conversation.setUpdatedAt(LocalDateTime.now());
            return updateById(conversation);
        }
        return false;
    }

    @Override
    public int getUnreadCount(Long conversationId, Long userId) {
        // 从 messages 表中查询未读消息数量
        LambdaQueryWrapper<com.yuelao.yuelao_backend.entity.Message> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(com.yuelao.yuelao_backend.entity.Message::getConversationId, conversationId)
               .eq(com.yuelao.yuelao_backend.entity.Message::getReceiverId, userId)
               .eq(com.yuelao.yuelao_backend.entity.Message::getIsRead, false)
               .eq(com.yuelao.yuelao_backend.entity.Message::getIsRevoked, false);
        
        long count = messageMapper.selectCount(wrapper);
        return count > Integer.MAX_VALUE ? Integer.MAX_VALUE : (int) count;
    }
}

